import { userlogin } from '../../request/api.js'
import { successMsg, failedMsg } from "../../tools/tools.js";

export default {
    //开启命名空间：防止不同模块中的数据或方法同名
    namespaced: true,
    state: {
        ruleForm: {
            username: "",
            password: "",
        },
        rules: {
            username: [
                { required: true, message: '请输入帐号', trigger: 'blur' },
                { min: 4, max: 12, message: '长度在4到12个字符', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' }
            ],
        },
        userManger: {}
    },
    mutations: {
        cahngeUserManger(state, obj) {
            state.userManger = obj
        },
        changerruleForm(state,obj){
            state.ruleForm = obj
        }
    },
    actions: {
        getUserInfo(context, obj) {
            if (!obj.username) {
                let uObj = localStorage['userManger'] ? JSON.parse(localStorage['userManger']) : {}
                context.commit('cahngeUserManger', uObj);
            }
        },
        submitForm(contxt, vm) {
            vm.$refs.ruleForm.validate((valid) => {
                if (valid) {  //帐号及密码格式校验通过
                    userlogin(vm.ruleForm).then(d => {
                        if (d.data.code == 200) {  //登录成功
                            successMsg('登录成功');
                            //将登录成功的用户身份信息保存到localStroage中：
                            localStorage['userManger'] = JSON.stringify(d.data.list)
                            //将登录成功的用户身份信息保存到Vuex中的state中:
                            contxt.commit('cahngeUserManger', d.data.list);
                            contxt.commit('changerruleForm',{})
                            vm.$router.push('/');
                        } else {  //登录失败
                            failedMsg(d.data.msg);
                        }
                    });
                } else {  //帐号及密码格式校验失败
                    failedMsg('帐号或密码格式不正确');
                }
            });
        },
        //退出登录
        logout(contxt,vm) {
            //删除localStorage中的数据
            localStorage.removeItem('userManger');
            //清除state中的userInfo中的数据
            contxt.commit('cahngeUserManger', {});
            vm.$router.push('/login');
        }

    },
    getters: {
        ruleForm(state) {
            return state.ruleForm
        },
        userManger(state) {
            return state.userManger
        },
        rules(state) {
            return state.rules
        }
    },
}